package com.jstyle.jclifexd.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.FitnessOptions;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.app.MyApplication;
import com.jstyle.jclifexd.daoManager.PathRecordDaoManager;
import com.jstyle.jclifexd.model.Device1755;
import com.jstyle.jclifexd.model.Device1860;
import com.jstyle.jclifexd.model.PathRecord;
import com.jstyle.jclifexd.model.gomore.GomoreInfo;
import com.jstyle.jclifexd.utils.GlobalConst;
import com.jstyle.jclifexd.utils.PermissionsUtil;
import com.jstyle.jclifexd.utils.RxBus;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;
import com.jstyle.jclifexd.utils.Utils;
import com.jstyle.jclifexd.view.BottomDialog;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
public class ThirdDataActivity extends BaseActivity {
    @BindView(R.id.button_googleFit)
    Button buttonGoogleFit;
    @BindView(R.id.button_strava)
    TextView buttonStrava;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.llbb)
    RelativeLayout llbb;
    private GoogleSignInAccount account;
    private int GOOGLE_SIGN_IN = 122;
    private int strava = 124;
    private static final String TAG = "ThirdDataActivity";
    private FitnessOptions fitnessOptions;
    private int GOOGLE_FIT_PERMISSIONS_REQUEST_CODE = 123;
    int status=0;//当前是否同后台数据同步，0没有上传过数据，1后台已经有数据需要最新数据同步
    String begintime=null;
    public static int count = 0;
    String uptime;
    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        ThirdDataActivity.count = count;
    }

    BottomDialog sportdailog;

    @SuppressLint({"HandlerLeak", "CheckResult"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third_data);
        ButterKnife.bind(this);
        sportdailog = new BottomDialog(ThirdDataActivity.this, R.layout.dialog_third);
        init();
        //设备是1860或1755显示stava
        if (MyApplication.getJstyleDevice() instanceof Device1755 || MyApplication.getJstyleDevice() instanceof Device1860) {
            llbb.setVisibility(View.VISIBLE);
            RxBus.getInstance().toObservable(Message.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Message>() {
                @Override
                public void accept(Message bleData) {
                    switch (bleData.what) {
                        case 0:
                            if (Utils.getRunningActivityName(ThirdDataActivity.this).contains("ThirdDataActivity")) {
                                buttonStrava.setText("Strava");
                            }
                            break;
                        case 1:
                            if (Utils.getRunningActivityName(ThirdDataActivity.this).contains("ThirdDataActivity")) {
                                buttonStrava.setText(bleData.obj.toString());
                            }
                            break;
                        case 2:
                            showToast(getString(R.string.submit_successfully));
                            if (null != anim) {
                                anim.stop();
                                img.setImageDrawable(getResources().getDrawable(R.drawable.share_strava));
                            } else {
                                img.setImageDrawable(getResources().getDrawable(R.drawable.share_strava));
                            }
                            break;
                    }

                }
            });
        }

    }

    private void init() {
        fitnessOptions = FitnessOptions.builder()
                .addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_WRITE)
                .addDataType(DataType.TYPE_DISTANCE_DELTA, FitnessOptions.ACCESS_WRITE)
                .addDataType(DataType.TYPE_CALORIES_EXPENDED, FitnessOptions.ACCESS_WRITE)
                .addDataType(DataType.TYPE_HEART_RATE_BPM, FitnessOptions.ACCESS_WRITE)
                .addDataType(DataType.TYPE_HEART_RATE_BPM, FitnessOptions.ACCESS_READ)
                .addDataType(DataType.TYPE_HEART_POINTS, FitnessOptions.ACCESS_WRITE)
                .addDataType(DataType.TYPE_HEART_POINTS, FitnessOptions.ACCESS_READ)
                .build();
        account = GoogleSignIn.getLastSignedInAccount(this);
        if (account != null) {
            if (GoogleSignIn.hasPermissions(account, fitnessOptions)) {
                buttonGoogleFit.setText("Connected");
            }
        }
    }

    @OnClick({R.id.button_googleFit, R.id.llbb})
    public void onViewClicked(View view) {
        if (Utils.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.button_googleFit:
                connectGoogle();
                break;
            case R.id.llbb:
                boolean ishsowdialog = SharedPreferenceUtils.getBoolean(GlobalConst.KEY_ishsowdialog, false);
                if (!ishsowdialog) {
                    ishsowdiag();
                } else {
                    //是否有网络
                    if (Utils.checkNetWork(this)) {
                        if (getCount() == 0&&!buttonStrava.getText().toString().equals(getString(R.string.Data_Synchronizing))) {
                            findtime();
                        } else {
                            showToast(getResources().getString(R.string.Data_Synchronizing));
                        }
                    } else {
                        showToast(this.getString(R.string.Network_not_availa));
                    }
                }
                break;
        }
    }



    private void ishsowdiag() {
        sportdailog.show();
        final Button refresh = sportdailog.getmView().findViewById(R.id.refresh);
        final Button start = sportdailog.getmView().findViewById(R.id.start);
        final Button cancel = sportdailog.getmView().findViewById(R.id.cancel);
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sportdailog.dismiss();
                startActivity(ExerciseRecordListActivity.class);
                SharedPreferenceUtils.setSpBoolean(GlobalConst.KEY_ishsowdialog, true);
            }
        });
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sportdailog.dismiss();
                //是否有网络
                if (Utils.checkNetWork(ThirdDataActivity.this)) {
                    if (getCount() == 0&&!buttonStrava.getText().toString().equals(getString(R.string.Data_Synchronizing))) {
                        findtime();
                    } else {
                        showToast(getResources().getString(R.string.Data_Synchronizing));
                    }
                } else {
                    showToast(ThirdDataActivity.this.getString(R.string.Network_not_availa));
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sportdailog.dismiss();
            }
        });
    }

    private void findtime() {
      // stravaLogin();
        String address= SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
       Map<String, Object> map = new HashMap<>();
        map.put("uid", NetWorkUtil.getUserId());
        map.put("mac", address==null?"":address);
        NetWorkUtil.getInstance().getJstyleApi().queryLastTime(map).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<GomoreInfo>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(GomoreInfo activitvtiesData) {
                //查询保存数据的时间是否与本地一致
                final List<PathRecord> pathRecordList = PathRecordDaoManager.getAllPathRecordByMode();
                if (pathRecordList.size() != 0) {
                    if(null == activitvtiesData.getData()){
                        status=0;
                        uptime = "20" + pathRecordList.get(0).getMDate().replace(".", "-");
                    }else{
                        status=1;
                        begintime=((activitvtiesData.getData().replace("-", ".")).substring(2)).split(" ")[0];
                        if(null!=begintime&&null!=PathRecordDaoManager.getLastPathRecord()&&null!=PathRecordDaoManager.getLastPathRecord().getMDate()){
                            String endtime=PathRecordDaoManager.getLastPathRecord().getMDate();
                            final List<PathRecord> pathRecordListA   = PathRecordDaoManager.getAllPathRecordByModefortime(begintime,endtime);
                            uptime = "20" + pathRecordListA.get(0).getMDate().replace(".", "-");
                        }
                    }
                  if (null == activitvtiesData.getData() || !activitvtiesData.getData().equals(uptime)) {
                        stravaLogin();
                    } else {
                        showToast(getResources().getString(R.string.notnewdata));
                    }
                } else {
                    showToast(ThirdDataActivity.this.getString(R.string.notnewdata));
                }
            }

            @Override
            public void onError(Throwable e) {
                showToast(ThirdDataActivity.this.getString(R.string.connection_timeout));
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void stravaLogin() {
        Intent intent = new Intent(ThirdDataActivity.this, StravaWebActivity.class);
        startActivityForResult(intent, strava);
    }

    public void connectGoogle() {
        try {
            //如果已经登录过google账号。则可以拿到账号
            account = GoogleSignIn.getLastSignedInAccount(this);
            if (account == null) {
                //没有。则要登录
                signIn();
            } else {
                //有，则要订阅
                Subscribe();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    private void signIn() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
        GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
    }

    private void Subscribe() {
        account = GoogleSignIn.getLastSignedInAccount(this);
        if (account == null) {
            return;
        }
        //判断是否有写入数据的权限，这个会弹出授权写入数据的弹框
        if (!GoogleSignIn.hasPermissions(account, fitnessOptions)) {
            GoogleSignIn.requestPermissions(
                    this, // your activity
                    GOOGLE_FIT_PERMISSIONS_REQUEST_CODE,
                    account,
                    fitnessOptions);
        } else {
            subscriptionData();
        }
    }

    private void subscriptionData() {
        subscribe(DataType.TYPE_STEP_COUNT_DELTA);// 订阅步数
        subscribe(DataType.TYPE_DISTANCE_DELTA);//
        PermissionsUtil.requestPermissions(this, new PermissionsUtil.PermissionListener() {
            @Override
            public void granted(String name) {
                subscribe(DataType.TYPE_HEART_RATE_BPM);//
            }

            @Override
            public void NeverAskAgain() {
            }

            @Override
            public void disallow(String name) {
            }
        }, Manifest.permission.BODY_SENSORS);


    }

    private void subscribe(final DataType dataType) {
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        if (account == null) {
            return;
        }
        Fitness.getRecordingClient(this, GoogleSignIn.getLastSignedInAccount(this))
                .subscribe(dataType)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        //每订阅成功一个，会回调这个方法

                        Log.i(TAG, "onSuccess: " + dataType.getName());
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.i(TAG, "onFailure: " + e.getMessage());
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == GOOGLE_FIT_PERMISSIONS_REQUEST_CODE) {
                subscriptionData();
            } else if (requestCode == GOOGLE_SIGN_IN) {
                Subscribe();
            }
        } else if (resultCode == strava) {
            buttonStrava.setText(getString(R.string.Data_Synchronizing));
            //授权
            count=0;
            showAnimation(0);
        }
    }

    AnimationDrawable anim = null;

    private void showAnimation(int type) {
        if (Utils.getRunningActivityName(ThirdDataActivity.this).contains("ThirdDataActivity")) {
            if (0 == type) {
                img.setImageResource(R.drawable.btn_anim);
                anim = (AnimationDrawable) img.getDrawable();
                anim.start();
            } else {
                Message message = new Message();
                message.what = 2;
                RxBus.getInstance().post(message);
            }
        }

    }










}
